﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SupermarketSalesController;
using SupermarketSalesModel;

namespace SalesApp
{
    class Program
    {
        public const int CAJA = 1;

        public static void login()
        {
            while (true)
            {
                Console.Clear();
                Console.WriteLine("\n===================BIENVENIDO===============\n");
                Console.WriteLine("1. Ingresar");
                Console.WriteLine("2. Salir");
                Console.Write("\nIngresar Opcion: ");
                int op = 0;
                try
                {
                    op = Int16.Parse(Console.ReadLine());

                    if (op == 1)
                    {
                        Console.Clear();
                        Console.WriteLine("\n===================BIENVENIDO===============\n");
                        Console.Write("Ingresar Codigo de Cajero: ");
                        int idSalesclerk = 0;
                        try
                        {
                            idSalesclerk = Int32.Parse(Console.ReadLine());

                            Salesclerk sc = SalesManager.getSalesclerkbyId(idSalesclerk);

                            if (sc != null)
                            {
                                while (callMenu(idSalesclerk) == 1) ;
                            }
                            else
                            {
                                Console.WriteLine("\nCajero no registrado");
                                Console.WriteLine("Presione Enter para continuar...");
                                Console.ReadLine();
                            }
                        }
                        catch (FormatException)
                        {
                            Console.WriteLine("\nOpcion invalida");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                    }
                    else if (op == 2)
                    {
                        if ((SalesManager.getAllProducts().Count) > 0)
                        {
                            SalesManager.PersistProductsDB();
                            SalesManager.PersistClientsDB();
                            SalesManager.PersistCashRegisterDB();
                            SalesManager.PersistClerkDB();
                            SalesManager.PersistCreditNoteDB();
                            SalesManager.PersistSaleDB();
                            //Aqui hay que colocar los demas persist's

                        }
                        Environment.Exit(0);
                    }
                }
                catch (FormatException)
                {
                    Console.WriteLine("\nOpcion invalida");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }
        }
        public static int callMenu(int idSalesclerk)
        {
            while (true)
            {
                Console.Clear();
                Console.WriteLine("\n===================MENU PRINCIPAL===============\n");
                Console.WriteLine("1. Mantenimientos");
                Console.WriteLine("2. Ingresar Nueva Venta"); 
                Console.WriteLine("3. Registrar Devolucion");
                Console.WriteLine("4. Salir");
                Console.Write("\nIngresar Opcion: ");
                int op = 0;
                try
                {
                    op = Int32.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("\nOpcion invalida");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }

                if (op == 1)
                {
                    while (doMaintenance() ==1) ;
                }
                else if (op == 2)  
                {
                    registerNewSale(idSalesclerk);

                }
                else if( op == 3)
                {
                    registerNewCN();
                }
                else if (op == 4)
                {
                    return 0;
                }
                else
                {
                    Console.WriteLine("\nOpcion Incorrecta");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
                return 1;
            }
        }

        /***Maintenance***/
        public static int doMaintenance()
        {
            Console.Clear();
            Console.WriteLine("\n===================MANTENIMIENTOS===============\n");
            Console.WriteLine("1. Clientes");
            Console.WriteLine("2. Productos");
            Console.WriteLine("3. Cajas");
            Console.WriteLine("4. Cajeros");
            Console.WriteLine("5. Regresar");
            Console.Write("\nIngresar Opcion: ");
            int op= 0;
            try
            {
                op = Int16.Parse(Console.ReadLine());
            }
            catch (FormatException)
            {
                Console.WriteLine("\nOpcion Invalida");
                Console.WriteLine("Presione Enter para continuar...");
                Console.ReadLine();
            }

            if (op == 1)
            {
                callSubmenuClients();
            }
            else if (op == 2)
            {
                callSubmenuProducts();
            }
            else if (op == 3)
            {
                callSubmenuCashRegister();
            }
            else if (op == 4)
            {
                callSubmenuSalesclerk();
            }
            else if (op == 5)
            {
                return 0;
            }
            else
            {
                Console.WriteLine("\nOpcion Invalida");
                Console.WriteLine("Presione Enter para continuar...");
                Console.ReadLine();
            }
            return 1;
        }

        public static void callSubmenuClients()
        {
            Console.Clear();
            Console.WriteLine("\n======================CLIENTES==================\n");
            int op2 = callMaintenanceSubmenu();
            if (op2 == 1)
            {
                updateClient();
            }
            else if (op2 == 2)
            {
                registerNewClient();
            }
            else if (op2 == 3)
            {
                return;
            }
            else
            {
                Console.WriteLine("\nOpcion Incorrecta");
                Console.WriteLine("Presione Enter para continuar...");
                Console.ReadLine();
            }
        }

        public static void callSubmenuProducts()
        {
            Console.Clear();
            Console.WriteLine("\n=====================PRODUCTOS==================\n");
            int op2 = callMaintenanceSubmenu();
            if (op2 == 1)
            {
                updateProduct();
            }
            else if (op2 == 2)
            {
                registerNewProduct();
            }
            else if (op2 == 3)
            {
                return;
            }
            else
            {
                Console.WriteLine("\nOpcion Incorrecta");
                Console.WriteLine("Presione Enter para continuar...");
                Console.ReadLine();
            }
        }

        public static void callSubmenuCashRegister()
        {
            Console.Clear();
            Console.WriteLine("\n=======================CAJAS====================\n");
            int op2 = callMaintenanceSubmenu();
            if (op2 == 1)
            {
                updateCashRegister();
            }
            else if (op2 == 2)
            {
                registerNewCashRegister();
            }
            else if (op2 == 3)
            {
                return;
            }
            else
            {
                Console.WriteLine("\nOpcion Incorrecta");
                Console.WriteLine("Presione Enter para continuar...");
                Console.ReadLine();
            }
        }

        public static void callSubmenuSalesclerk()
        {
            Console.Clear();
            Console.WriteLine("\n======================CAJEROS===================\n");
            int op2 = callMaintenanceSubmenu();
            if (op2 == 1)
            {
                updateSalesclerk();
            }
            else if (op2 == 2)
            {
                registerNewSalesclerk();
            }
            else if (op2 == 3)
            {
                return;
            }
            else
            {
                Console.WriteLine("\nOpcion Incorrecta");
                Console.WriteLine("Presione Enter para continuar...");
                Console.ReadLine();
            }
        }

        public static int callMaintenanceSubmenu()
        {
            Console.WriteLine("1. Consultar (Mostrar/Modificar/Eliminar)");
            Console.WriteLine("2. Agregar");
            Console.WriteLine("3. Regresar");
            Console.Write("\nIngresar Opcion: ");
            int op = 0;
            try
            {
                op = Int32.Parse(Console.ReadLine());
            }
            catch (FormatException)
            {
                Console.WriteLine("Opcion invalida");
                Console.ReadLine();
            }
            return op;
        }

        /***Client Maintenance***/
        public static void registerNewClient()
        {
            Console.Clear();
            Console.WriteLine("\n======================CLIENTES==================\n");
            Console.Write("Ingresar DNI Cliente: ");
            String idCard = Console.ReadLine();

            Console.Write("\nIngresar Nombre Cliente: ");
            String name = Console.ReadLine();

            Console.Write("\nIngresar Apellido Cliente: ");
            String lastname = Console.ReadLine();

            DateTime bornDate = DateTime.MinValue;
            while (bornDate.Equals(DateTime.MinValue))
            {
                Console.Write("\nIngresar Fecha Nac. Cliente (DD/MM/YYYY): ");
                try
                {
                    bornDate = Convert.ToDateTime(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("\nFecha invalida");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }

            int telnum = 0;
            while (telnum == 0)
            {
                Console.Write("\nIngresar Telefono Cliente: ");
                try
                {
                    telnum = Int32.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("\nTelefono invalido");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }

            Console.Write("\nIngresar Email Cliente: ");
            String email = Console.ReadLine();

            int idClient = SalesManager.getAllClients().Count + 1;

            Console.Write("\nIngresar Numero de Tarjeta Cliente: ");
            String cardNumber = Console.ReadLine();

            int cat = 0;
            while (cat == 0){
                Console.WriteLine("\nCategoria de Cliente: ");
                Console.WriteLine("1. Normal");
                Console.WriteLine("2. Preferencial");
                Console.Write("\nElegir Categoria: ");
                try
                {
                    cat = Int16.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("\nOpcion Invalida");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }

            String category = null;
            switch (cat)
            {
                case 1: category = "Normal"; break;
                case 2: category = "Preferencial"; break;
                default: Console.WriteLine("Opcion Incorrecta"); break;
            }

            Client c = new Client(idCard, name, lastname, bornDate, DateTime.Now, telnum, email, idClient, cardNumber, category);
            SalesManager.addClient(c);
            Console.WriteLine("\nNuevo Cliente Registrado");
            Console.WriteLine("Presione Enter para continuar...");
            Console.ReadLine();
        }

        public static void updateClient()
        {
            int op3 = 0;
            while (op3 == 0)
            {
                Console.Clear();
                Console.WriteLine("\n======================CLIENTES==================\n");
                Console.WriteLine("1. Mostrar");
                Console.WriteLine("2. Modificar");
                Console.WriteLine("3. Eliminar");
                Console.WriteLine("4. Regresar");
                Console.Write("\nIngresar Opcion: ");
                try
                {
                    op3 = Int32.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("\nOpcion invalida");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }

            if (op3 > 0 && op3 <= 4)
            {
                Console.Clear();
                Console.WriteLine("\n======================CLIENTES==================\n");
                Console.Write("Ingresar DNI Cliente: ");
                String dniClient = Console.ReadLine();
                Client c = SalesManager.getClientbyIdCard(dniClient);

                if (c != null)
                {
                    if (op3 == 1)
                    {
                        Console.WriteLine();
                        Console.WriteLine(c);
                        Console.WriteLine(c.Email);
                        Console.WriteLine(c.TelephoneNumber);
                        Console.WriteLine("\nPresione Enter para continuar...");
                        Console.ReadLine();
                    }
                    else if (op3 == 2)
                    {
                        int op4 = 0;
                        while (op4 == 0)
                        {
                            Console.Clear();
                            Console.WriteLine("\n======================CLIENTES==================\n");
                            Console.WriteLine("¿Que desea modificar?");
                            Console.WriteLine("\n1. Telefono");
                            Console.WriteLine("2. Email");
                            Console.WriteLine("3. Cancelar");
                            Console.Write("\nIngresar Opcion: ");

                            try
                            {
                                op4 = Int32.Parse(Console.ReadLine());
                            }
                            catch (FormatException)
                            {
                                Console.WriteLine("\nOpcion invalida");
                                Console.WriteLine("Presione Enter para continuar...");
                                Console.ReadLine();
                            }
                        }

                        if (op4 == 1)
                        {
                            int tel = 0;
                            while (tel == 0)
                            {
                                Console.Clear();
                                Console.WriteLine("\n======================CLIENTES==================\n");
                                Console.WriteLine("Telefono Actual: " + c.TelephoneNumber);
                                Console.Write("Nuevo Telefono: ");
                                try
                                {
                                    tel = Int32.Parse(Console.ReadLine());
                                }
                                catch (FormatException)
                                {
                                    Console.WriteLine("\nTelefono invalido");
                                    Console.WriteLine("Presione Enter para continuar...");
                                    Console.ReadLine();
                                }
                                catch (OverflowException)
                                {
                                    Console.WriteLine("\nTelefono excede la cantidad de numeros permitidos");
                                    Console.WriteLine("Presione Enter para continuar...");
                                    Console.ReadLine();
                                }
                                c.TelephoneNumber = tel;
                                Console.WriteLine("\nTelefono Actualizado");
                                Console.WriteLine("Presione Enter para continuar...");
                                Console.ReadLine();
                            }

                        }
                        else if (op4 == 2)
                        {
                            Console.Clear();
                            Console.WriteLine("\n======================CLIENTES==================\n");
                            Console.WriteLine("Email Actual: " + c.Email);
                            Console.Write("Nuevo Email: ");
                            String email = Console.ReadLine();
                            c.Email = email;
                            Console.WriteLine("\nEmail Actualizado");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                        else if (op4 == 3)
                        {
                            return;
                        }
                        else
                        {
                            Console.WriteLine("\nOpcion Incorrecta");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                    }
                    else if (op3 == 3)
                    {
                        Console.Clear();
                        Console.WriteLine("\n======================CLIENTES==================\n");
                        Console.Write("¿Esta seguro que desea eliminar al Cliente " + c.Name + " " + c.Lastname + " (S/N)?: ");
                        String resp = Console.ReadLine();

                        if (resp.Equals("S") || resp.Equals("s"))
                        {
                            SalesManager.deleteClient(dniClient);
                            Console.WriteLine("\nCliente Eliminado");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                        else if (resp.Equals("N"))
                        {
                            Console.WriteLine("\nNo se elimino");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                    }
                    else if (op3 == 4)
                    {
                        return;
                    }
                }
                else
                {
                    Console.WriteLine("\nCliente No Encontrado");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }
            else
            {
                Console.WriteLine("\nOpcion Incorrecta");
                Console.WriteLine("Presione Enter para continuar...");
                Console.ReadLine();
            }
        }

        /***Product Maintenance***/
        public static void registerNewProduct()
        {
            Console.Clear();
            Console.WriteLine("\n=====================PRODUCTOS==================\n");

            int idProduct = SalesManager.getAllProducts().Count + 1;

            Console.Write("Ingresar Descripcion Producto: ");
            String desc = Console.ReadLine();

            Console.Write("\nIngresar EAN Producto: ");
            String ean = Console.ReadLine();

            Double basePrice = -1;
            while (basePrice == -1)
            {
                Console.Write("\nIngresar Precio Base Producto: ");

                try
                {
                    basePrice = Double.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("\nOpcion invalida");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }

            Console.Write("\nIngresar Marca Producto: ");
            String brand = Console.ReadLine();

            Console.Write("\nIngresar Tipo Producto: ");
            String type = Console.ReadLine();

            Product p = new Product(idProduct, desc, ean, basePrice, brand, type);
            SalesManager.addProduct(p);
            Console.WriteLine("Nuevo Producto Registrado");
            Console.WriteLine("Presione Enter para continuar...");
            Console.ReadLine();
        }

        public static void updateProduct()
        {
            int op3 = 0;
            while (op3 == 0)
            {
                Console.Clear();
                Console.WriteLine("\n=====================PRODUCTOS==================\n");
                Console.WriteLine("1. Mostrar");
                Console.WriteLine("2. Modificar");
                Console.WriteLine("3. Eliminar");
                Console.WriteLine("4. Regresar");
                Console.Write("\nIngresar Opcion: ");
                op3 = 0;
                try
                {
                    op3 = Int32.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("\nOpcion invalida");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }

            if (op3 > 0 && op3 <= 4)
            {
                int idProduct = 0;
                while (idProduct == 0)
                {
                    Console.Clear();
                    Console.WriteLine("\n=====================PRODUCTOS==================\n");
                    Console.Write("Ingresar Id Producto: ");
                    try
                    {
                        idProduct = Int32.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("\nOpcion invalida");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();
                    }
                }

                Product p = SalesManager.getProductbyId(idProduct);

                if (p != null)
                {
                    if (op3 == 1)
                    {
                        Console.WriteLine(p);
                       
                        Console.WriteLine("\nPresione Enter para continuar...");
                        Console.ReadLine();
                    }
                    else if (op3 == 2)
                    {
                        int op4 = 0;
                        while (op4 == 0)
                        {
                            Console.Clear();
                            Console.WriteLine("\n=====================PRODUCTOS==================\n");
                            Console.WriteLine("¿Que desea modificar?");
                            Console.WriteLine("\n1. Descripcion");
                            Console.WriteLine("2. Precio Base");
                            Console.WriteLine("3. Marca");
                            Console.WriteLine("4. Tipo Producto");
                            Console.WriteLine("5. Cancelar");
                            Console.Write("\nIngresar Opcion: ");
                            try
                            {
                                op4 = Int32.Parse(Console.ReadLine());
                            }
                            catch (FormatException)
                            {
                                Console.WriteLine("\nOpcion invalida");
                                Console.WriteLine("Presione Enter para continuar...");
                                Console.ReadLine();
                            }
                        }
                        if (op4 == 1)
                        {
                            Console.Clear();
                            Console.WriteLine("\n=====================PRODUCTOS==================\n");
                            Console.WriteLine("Descripcion Actual: " + p.Description);
                            Console.Write("Nueva Descripcion: ");
                            String desc = Console.ReadLine();
                            p.Description = desc;
                            Console.WriteLine("\nDescripcion Actualizada");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                        else if (op4 == 2)
                        {
                            Double price = -1;
                            while (price == -1)
                            {
                                Console.Clear();
                                Console.WriteLine("\n=====================PRODUCTOS==================\n");
                                Console.WriteLine("Precio Base Actual: " + p.BasePrice);
                                Console.WriteLine("Nuevo Precio Base: ");
                                try
                                {
                                    price = Double.Parse(Console.ReadLine());
                                }
                                catch (FormatException)
                                {
                                    Console.WriteLine("\nOpcion invalida");
                                    Console.WriteLine("Presione Enter para continuar...");
                                    Console.ReadLine();
                                }
                            }
                            p.BasePrice = price;
                            Console.WriteLine("\nPrecio Actualizado");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                        else if (op4 == 3)
                        {
                            Console.Clear();
                            Console.WriteLine("\n=====================PRODUCTOS==================\n");
                            Console.WriteLine("Marca Actual: " + p.Description);
                            Console.Write("Nueva Marca: ");
                            String brand = Console.ReadLine();
                            p.Brand = brand;
                            Console.WriteLine("\nMarca Actualizada");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                        else if (op4 == 4)
                        {
                            Console.Clear();
                            Console.WriteLine("\n=====================PRODUCTOS==================\n");
                            Console.WriteLine("Tipo Producto Actual: " + p.Description);
                            Console.Write("Nuevo Tipo Producto: ");
                            String type = Console.ReadLine();
                            p.Type = type;
                            Console.WriteLine("\nTipo Producto Actualizado");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                        else if (op4 == 5)
                        {
                            return;
                        }
                        else
                        {
                            Console.WriteLine("\nOpcion Incorrecta");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                    }
                    else if (op3 == 3)
                    {
                        Console.Clear();
                        Console.WriteLine("\n=====================PRODUCTOS==================\n");
                        Console.Write("¿Esta seguro que desea eliminar al Producto " + p.Description + " - " + p.Brand + " (S/N)?: ");
                        String resp = Console.ReadLine();

                        if (resp.Equals("S") || resp.Equals("s"))
                        {
                            SalesManager.deleteProduct(idProduct);
                            Console.WriteLine("\nCliente Eliminado");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                        else if (resp.Equals("N"))
                        {
                            Console.WriteLine("\nNo se elimino");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                    }
                    else if (op3 == 4)
                    {
                        return;
                    }
                }
                else
                {
                    Console.WriteLine("\nProducto no registrado");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }
            else
            {
                Console.WriteLine("\nOpcion Incorrecta");
                Console.WriteLine("Presione Enter para continuar...");
                Console.ReadLine();
            }
        }

        /***Cash Register Maintenance***/
        public static void registerNewCashRegister()
        {
            Console.Clear();
            Console.WriteLine("\n=======================CAJAS====================\n");
            int idCr = SalesManager.getAllCashRegisters().Count + 1;

            Console.Write("Ingresar Descripcion Caja: ");
            String desc = Console.ReadLine();

            CashRegister cr = new CashRegister(idCr, desc);
            SalesManager.addCr(cr);
            Console.WriteLine("\nNueva Caja Registrada");
            Console.WriteLine("Presione Enter para continuar...");
            Console.ReadLine();
        }

        public static void updateCashRegister()
        {
            int op3 = 0;
            while (op3 == 0)
            {
                Console.Clear();
                Console.WriteLine("\n=======================CAJAS====================\n");
                Console.WriteLine("1. Mostrar");
                Console.WriteLine("2. Modificar");
                Console.WriteLine("3. Eliminar");
                Console.WriteLine("4. Regresar");
                Console.Write("\nIngresar Opcion: ");
                try
                {
                    op3 = Int32.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("\nOpcion invalida");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }

            if (op3 > 0 && op3 <= 4)
            {
                int idCr = 0;
                while (idCr == 0)
                {
                    Console.Clear();
                    Console.WriteLine("\n=======================CAJAS====================\n");
                    Console.Write("\nIngresar Id caja: ");
                    try
                    {
                        idCr = Int32.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("\nId invalido");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();
                    }
                }  
                CashRegister cr = SalesManager.getCRbyId(idCr);

                if (cr != null)
                {

                    if (op3 == 1)
                    {
                        Console.WriteLine(cr);
                        Console.ReadLine();
                    }
                    else if (op3 == 2)
                    {
                        Console.Clear();
                        Console.WriteLine("\n=======================CAJAS====================\n");
                        Console.WriteLine("Descripcion Actual: " + cr.Description);
                        Console.Write("Nueva Descripcion: ");
                        String desc = Console.ReadLine();
                        cr.Description = desc;
                        Console.WriteLine("\nCaja Actualizada");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();
                    }
                    else if (op3 == 3)
                    {
                        Console.Clear();
                        Console.WriteLine("\n=======================CAJAS====================\n");
                        Console.Write("¿Esta seguro que desea inhabilitar la Caja " + cr.Id + " - " + cr.Description + " (S/N)?: ");
                        String resp = Console.ReadLine();

                        if (resp.Equals("S") || resp.Equals("s"))
                        {
                            SalesManager.deleteCashRegister(idCr);
                            Console.WriteLine("\nCaja inhabilitada");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                        else if (resp.Equals("N"))
                        {
                            Console.WriteLine("\nNo se realizo ningun proceso");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                    }
                    else if (op3 == 4)
                    {
                        return;
                    }
                }
                else
                {
                    Console.WriteLine("\nCaja no Registrada");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }
            else
            {
                Console.WriteLine("\nOpcion Incorrecta");
                Console.WriteLine("Presione Enter para continuar...");
                Console.ReadLine();
            }
        }

        /***Salesclerk Maintenance***/
        public static void registerNewSalesclerk()
        {
            Console.Clear();
            Console.WriteLine("\n======================CAJEROS===================\n");
            Console.Write("Ingresar DNI Cajero: ");
            String idCard = Console.ReadLine();

            Console.Write("\nIngresar Nombre Cajero: ");
            String name = Console.ReadLine();

            Console.Write("\nIngresar Apellido Cajero: ");
            String lastname = Console.ReadLine();

            DateTime bornDate = DateTime.MinValue;
            while (bornDate.Equals(DateTime.MinValue))
            {
                Console.Write("\nIngresar Fecha Nac. Cajero (DD/MM/YYYY): ");
                try
                {
                    bornDate = Convert.ToDateTime(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("\nFecha invalida");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }

            int telnum = 0;
            while (telnum == 0)
            {
                Console.Write("\nIngresar Telefono Cajero: ");
                try
                {
                    telnum = Int32.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("\nTelefono invalido");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }

            Console.Write("\nIngresar Email Cajero: ");
            String email = Console.ReadLine();

            int idSc = SalesManager.getAllSalesclerks().Count + 1;

            Console.Write("\nIngresar Observaciones: ");
            String obs = Console.ReadLine();

            Salesclerk sc = new Salesclerk(idCard, name, lastname, bornDate,DateTime.Now, telnum, email, idSc, obs);
            SalesManager.addSalesclerk(sc);
            Console.WriteLine("\nNuevo Cajero Registrado");
            Console.WriteLine("Presione Enter para continuar...");
            Console.ReadLine();
        }

        public static void updateSalesclerk()
        {
            int op3 = 0;
            while (op3 == 0)
            {
                Console.Clear();
                Console.WriteLine("\n======================CAJEROS===================\n");
                Console.WriteLine("1. Mostrar");
                Console.WriteLine("2. Modificar");
                Console.WriteLine("3. Eliminar");
                Console.WriteLine("4. Regresar");
                Console.Write("\nIngresar Opcion: ");
                try
                {
                    op3 = Int32.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("\nOpcion invalida");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }

            if (op3 > 0 && op3 <= 4)
            {
                int idSc = 0;
                while (idSc == 0)
                {
                    Console.Clear();
                    Console.WriteLine("\n======================CAJEROS===================\n");
                    Console.Write("Ingresar Id Cajero: ");
                    try
                    {
                        idSc = Int16.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("\nId invalido");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();
                    }
                }
                Salesclerk sc = SalesManager.getSalesclerkbyId(idSc);

                if (op3 == 1)
                {
                    Console.WriteLine();
                    Console.WriteLine(sc);
                    Console.WriteLine(sc.Email);
                    Console.WriteLine(sc.TelephoneNumber);
                    Console.WriteLine("\nPresione Enter para continuar...");
                    Console.ReadLine();
                }
                else if (op3 == 2)
                {
                    int op4 = 0;
                    while (op4 == 0)
                    {
                        Console.Clear();
                        Console.WriteLine("\n======================CAJEROS===================\n");
                        Console.WriteLine("¿Que desea modificar?");
                        Console.WriteLine("\n1. Telefono");
                        Console.WriteLine("2. Email");
                        Console.WriteLine("3. Observaciones");
                        Console.WriteLine("4. Cancelar");
                        Console.Write("\nIngresar Opcion: ");
                        try
                        {
                            op4 = Int32.Parse(Console.ReadLine());
                        }
                        catch (FormatException)
                        {
                            Console.WriteLine("\nOpcion invalida");
                            Console.WriteLine("Presione Enter para continuar...");
                            Console.ReadLine();
                        }
                    }

                    if (op4 == 1)
                    {
                        int tel = 0;
                        while (tel == 0)
                        {
                            Console.Clear();
                            Console.WriteLine("\n======================CAJEROS===================\n");
                            Console.WriteLine("Telefono Actual: " + sc.TelephoneNumber);
                            Console.Write("Nuevo Telefono: ");
                            try
                            {
                                tel = Int32.Parse(Console.ReadLine());
                            }
                            catch (FormatException)
                            {
                                Console.WriteLine("\nTelefono invalido");
                                Console.WriteLine("Presione Enter para continuar...");
                                Console.ReadLine();
                            }
                            catch (OverflowException)
                            {
                                Console.WriteLine("\nTelefono excede la cantidad de numeros permitidos");
                                Console.WriteLine("Presione Enter para continuar...");
                                Console.ReadLine();
                            }
                        }
                        sc.TelephoneNumber = tel;
                        Console.WriteLine("\nTelefono Actulizado");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();
                    }
                    else if (op4 == 2)
                    {
                        Console.Clear();
                        Console.WriteLine("\n======================CAJEROS===================\n");
                        Console.WriteLine("Email Actual: " + sc.Email);
                        Console.WriteLine("Nuevo Email: ");
                        String email = Console.ReadLine();
                        sc.Email = email;
                        Console.WriteLine("\nEmail Actualizado");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();

                    }
                    else if (op4 == 3)
                    {
                        Console.Clear();
                        Console.WriteLine("\n======================CAJEROS===================\n");
                        Console.WriteLine("Observaciones Actual: " + sc.Observations);
                        Console.WriteLine("Nuevas observaciones: ");
                        String obs = Console.ReadLine();
                        sc.Observations = obs;

                        Console.WriteLine("\nObservaciones Actualizadas");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();
                    }
                    else if (op4 == 4)
                    {
                        return;
                    }
                    else
                    {
                        Console.WriteLine("\nOpcion Incorrecta");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();
                    }
                }
                else if (op3 == 3)
                {
                    Console.Clear();
                    Console.WriteLine("\n======================CAJEROS===================\n");
                    Console.Write("¿Esta seguro que desea eliminar al Cajero " + sc.Name + " " + sc.Lastname + " (S/N): ");
                    String resp = Console.ReadLine();

                    if (resp.Equals("S") || resp.Equals("s"))
                    {
                        SalesManager.deleteSalesclerk(idSc);
                        Console.WriteLine("\nCajero Eliminado");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();
                    }
                    else if (resp.Equals("N"))
                    {
                        Console.WriteLine("\nNo se elimino al Cajero");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();
                    }
                }
                else if (op3 == 4)
                {
                    return;
                }
            }
            else
            {
                Console.WriteLine("\nOpcion Incorrecta");
                Console.WriteLine("Presione Enter para continuar...");
                Console.ReadLine();
            }

        }

        /***New Sale***/
        public static void registerNewSale(int idSalesclerk)
        {
            Sale s = new Sale();

            s.Id = SalesManager.getAllSales().Count() + 1;
            s.CashReg = SalesManager.getCRbyId(CAJA);
            s.Clerk = SalesManager.getSalesclerkbyId(idSalesclerk);
            s.SaleDate = DateTime.Now;


            Console.Write("\nIngresar DNI del cliente: ");
            String dni = (Console.ReadLine());
            Client c = SalesManager.getClientbyIdCard(dni);
            s.Client = c;
            
            while (true)
            {
                Console.Clear();
                Console.WriteLine("\n===================REGISTRO DE VENTA===============\n");
                Console.WriteLine("1. Agregar Producto");
                Console.WriteLine("2. Eliminar Producto");
                if (s.Details.Count > 0)
                {
                    Console.WriteLine("3. Finalizar Venta\n");
                }
                else
                {
                    Console.WriteLine("3. Cancelar Venta\n");
                }
                Console.Write("\nIngresar Opcion: ");
                try
                {
                    int op = Int32.Parse(Console.ReadLine());
                    if (op == 1) askProduct(s);
                    else if ((op == 2) && (s.Details.Count > 0)) deleteProduct(s);
                    else if ((op == 2) && (s.Details.Count == 0))
                    {
                        Console.WriteLine("\nNo se ha agregado ningun producto");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();
                    }
                    else if ((op == 3) && (s.Details.Count > 0))
                    {
                        finishSale(s);
                        break;
                    }
                    else if ((op == 3) && (s.Details.Count == 0))
                    {
                        break;
                    }
                }
                catch (FormatException)
                {
                        Console.WriteLine("\nOpcion Incorrecta");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();
                }
            }
        }

        public static void askProduct(Sale s)
        {
            Console.Clear();
            Console.Write("\n===================REGISTRO VENTA===============\n");
            Console.Write("\nIngrese codigo producto: ");
            int cod = Int32.Parse(Console.ReadLine());

            Product p = SalesManager.getProductbyId(cod);
            if (p != null)
            {
                Console.Write("Ingrese cantidad: ");
                int cant = Int32.Parse(Console.ReadLine());
                s.addDetail(SalesManager.getProductbyId(cod), cant);
            }
            else
            {
                Console.WriteLine("\nCodigo de producto incorrecto");
                Console.WriteLine("Presione Enter para continuar...");
                Console.ReadLine();
            }

        }

        public static void deleteProduct(Sale s)
        {
            Console.Write("\nIngrese codigo producto: ");
            int cod = 0;
            try
            {
                cod = Int32.Parse(Console.ReadLine());
            }
            catch (FormatException)
            {
                Console.WriteLine("\nCodigo Incorrecto");
                Console.WriteLine("Presione Enter para continuar...");
                Console.ReadLine();             
            }
            if (cod > 0)
            {
                Product p = null;
                foreach (SalesDetail sd in s.Details)
                { //buscar en la venta
                    if (sd.Product.Id == cod)
                    {
                        p = sd.Product;
                    }
                }

                if (p != null) //si el producto ya estaba agregado
                {
                    Console.Write("Ingrese cantidad a eliminar: ");
                    int cant = 0;
                    try
                    {
                        cant = Int32.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("\nCantidad Incorrecta");
                        Console.WriteLine("Presione Enter para continuar...");
                        Console.ReadLine();
                    }
                    if (cant > 0)
                    {
                        s.addDetail(SalesManager.getProductbyId(cod), cant * (-1));
                    }
                }
                else
                {
                    Console.WriteLine("\nEl producto no pertenece a la venta actual");
                    Console.WriteLine("Presione Enter para continuar...");
                    Console.ReadLine();
                }
            }
           
        }

        public static void finishSale(Sale s)
        {
            Console.Clear();
            Console.WriteLine("\n===================REGISTRO DE VENTA===============\n");
            Console.Write("Total a Pagar: " + s.TotalAmount);
            while (true)
            {
                Console.Write("\nEfectivo a ingresar: ");
                double cant = Double.Parse(Console.ReadLine());
                if (cant < s.TotalAmount)
                {
                    Console.WriteLine("\nDinero Insuficiente para realizar la compra");
                }
                else
                {
                    s.finish(cant);
                    SalesManager.addSale(s);
                    break;
                }
            }
            Console.Clear();
            Console.WriteLine("\n===================REGISTRO DE VENTA===============\n");
            Console.WriteLine("Comprobante de Pago:");
            Console.WriteLine("1. Boleta");
            Console.WriteLine("2. Factura");
            Console.Write("\nIngrese Opcion: ");
            int cp = Int16.Parse(Console.ReadLine());

            if (cp == 1)
            {
                printTicket(s,null,0);
            }
            else if (cp == 2)
            {
                Console.Clear();
                Console.WriteLine("\n===================REGISTRO DE VENTA===============\n");
                Console.Write("\nIngrese Razon Social: ");
                String rs = Console.ReadLine();
                Console.Write("\nIngrese Numero de RUC: ");
                Int64 ruc = Int64.Parse(Console.ReadLine());

                printTicket(s, rs, ruc);
            }
        }

        public static void printTicket(Sale s, String rs, Int64 ruc)
        {
            Console.Clear();
            Console.WriteLine("\n===============================================================");
            Console.WriteLine( "                       HIPERMERCADO LP2                         ");
            Console.Write("\n\t{0,-10}{1, 8}", "Num. Ticket ", s.Id);
            Console.WriteLine("\t\t{0,-10}{1, 8}", "Caja # ", s.CashReg.Id);
            Console.Write("\n\t{0,-10}{1, 8}", "Fecha: ", s.SaleDate.ToString("d/MMM/yyyy"));
            Console.WriteLine("\t\t{0,-10}{1, 8}", "Hora: ", s.SaleDate.ToString("HH:mm:ss") + "\n");

            Console.WriteLine("\tVendedor: " + s.Clerk);
            Console.WriteLine("\tCliente: " + s.Client);

            if (rs != null)
            {
                Console.WriteLine("\n\tRazon Social: " + rs);
                Console.WriteLine("\tRUC: " + ruc);
            }

            Console.WriteLine("\n---------------------------------------------------------------\n");
            string header = String.Format("  {0,-8}{1,-30}{2,10}{3,10}\n",
                                    "Cant", "Producto", "P.U", "Subtotal");
            Console.WriteLine(header);
            foreach (SalesDetail sd in s.Details)
            {
                string detail = String.Format("  {0,-8}{1,-30}{2,10:N2}{3,10:N2}\n",
                                    sd.Quantity, sd.Product, sd.Product.BasePrice, sd.SubTotal);
                Console.WriteLine(detail);
            }
            Console.WriteLine("\n---------------------------------------------------------------\n");
            Console.WriteLine("{0,50}{1,10:N2}", "Subtotal:", s.SubTotalAmount);
            Console.WriteLine("{0,50}{1,10:N2}", "IGV:", s.TotalAmount - s.SubTotalAmount);
            Console.WriteLine("{0,50}{1,10:N2}", "Total:", s.TotalAmount);
            Console.WriteLine("\n{0,50}{1,10:N2}", "Efectivo:", s.PaidAmount);
            Console.WriteLine("{0,50}{1,10:N2}", "Vuelto:", s.PaidAmount - s.TotalAmount);

            Console.WriteLine("\n---------------------------------------------------------------\n");
            if (s.Client==null)
            {
                Console.WriteLine("\t\tHubieras ganado " + s.WonPoints +" puntos");
            }
            else
            {
                Console.WriteLine("\t\tHas ganado " + s.WonPoints + " puntos");
                Console.WriteLine("\t\tPuntos acumulados " + s.Client.Points + " puntos");
            }
            Console.WriteLine("\n===============================================================\n");

            Console.WriteLine("Presione Enter para continuar");
            Console.ReadLine();
        }
        
        /***New Credit Note***/
        public static void registerNewCN()
        {
            //1. ingresar num venta
            Console.Write("\nIngresar numero de venta: ");
            int idSale = Int32.Parse(Console.ReadLine());
            //buscar venta
            Sale sale = SalesManager.getSaleById(idSale);

            //2. si existe venta-> verificar 7 dias
            if (sale != null)
            {
                if (DateTime.Now.Subtract(sale.SaleDate).Days <= 7)
                {
                    CreditNote cn = new CreditNote(SalesManager.getAllCreditNotes().Count, sale);

                    while (true)
                    {
                        Console.Clear();
                        //Print venta
                        printTicket(sale, null, 0);
                        Console.WriteLine("\n");
                        Console.WriteLine("\n===================REGISTRO NOTA DE CREDITO===============\n");
                        Console.WriteLine("1. Agregar Producto");
                        Console.WriteLine("2. Eliminar Producto");
                        Console.WriteLine("3. Finalizar Nota de Credito\n");
                        Console.Write("Ingresar Opcion: ");
                        int op = Int32.Parse(Console.ReadLine());
                        if (op == 1) askProductCN(cn);
                        else if (op == 2) deleteProductCN(cn);
                        else if (op == 3)
                        {
                            finishCN(cn);
                            break;
                        }
                        else
                        {
                            Console.WriteLine("Opcion Incorrecta");
                        }
                        
                    }
                }
                else
                {
                    Console.WriteLine("->El tiempo transcurrido es mayor al Tiempo limite para realizar el reclamo\n");
                }
            }
            else
            {
                Console.WriteLine("Error: Venta no registrada\n");
            }
        }

        public static void askProductCN(CreditNote cn)
        {
            Console.Write("\nIngrese codigo de producto a devolver: ");
            int cod = Int32.Parse(Console.ReadLine());

            Console.Write("Ingrese cantidad: ");
            int cant = Int32.Parse(Console.ReadLine());

            Console.Write("Ingrese precio registrado: ");
            double price = Double.Parse(Console.ReadLine());

            cn.addDetail(SalesManager.getProductbyId(cod), cant, price);
        }

        public static void deleteProductCN(CreditNote cn)
        {
            Console.Write("\nIngrese codigo producto: ");
            int cod = Int32.Parse(Console.ReadLine());

            Console.Write("Ingrese cantidad a disminuir: ");
            int cant = Int32.Parse(Console.ReadLine());

            Console.Write("Ingrese precio registrado: ");
            double price = Double.Parse(Console.ReadLine());

            cn.addDetail(SalesManager.getProductbyId(cod), cant * (-1), price);
        }

        public static void finishCN(CreditNote cn)
        {
            SalesManager.addCreditNote(cn);
            printCN(cn);
        }

        public static void printCN(CreditNote cn)
        {
            Console.Clear();
            Console.WriteLine("\n===============================================================");
            Console.WriteLine("\t\tHIPERMERCADO LP2"); 
            Console.Write("\n\t{0,-10}{1, 8}", "Nota de Credito ", cn.Id);
            Console.Write("\n\t{0,-10}{1, 8}", "Fecha: ", cn.RegisterDate.ToString("d/MMM/yyyy"));
            Console.WriteLine("\t\t{0,-10}{1, 8}", "Hora: ", cn.RegisterDate.ToString("HH:mm:ss"));

            Console.WriteLine("\n\tCliente: " + cn.Sale.Client);
            Console.WriteLine("\n---------------------------------------------------------------\n");

            string header = String.Format("  {0,-8}{1,-30}{2,10}{3,10}\n",
                                    "Cant", "Producto", "P.U", "Subtotal");
            Console.WriteLine(header);
            foreach (CNDetail cnd in cn.Details)
            {
                string detail = String.Format("  {0,-8}{1,-30}{2,10:N2}{3,10:N2}\n",
                                    cnd.Quantity, cnd.Product, cnd.Product.BasePrice, cnd.SubTotal);
                Console.WriteLine(detail);
            }
            Console.WriteLine("\n---------------------------------------------------------------\n");

            Console.WriteLine("{0,50}{1,10:N2}", "Total:", cn.Amount);

            Console.WriteLine("\n===============================================================\n");

            Console.WriteLine("Presione Enter para continuar");
            Console.ReadLine();
        }

        static void Main(string[] args)
        {
            //Console.SetWindowPosition(0,0);
            //Console.SetWindowSize(180,69);

            Console.SetWindowSize(Console.WindowWidth*2, Console.WindowHeight*2);
            
            /*
            Product p1 = new Product(1, "Cuaderno", "12341231", 5, "Standford", "Articulos de Oficina");
            Product p2 = new Product(2, "Lapicero", "21840124", 2, "Xinghua", "Articulos de Oficina");
            Product p3 = new Product(3, "Calculadora Cientifica", "'28490719", 500, "HP", "Articulos de Oficina");
            Product p4 = new Product(4, "Mochila", "12812314", 60, "Porta", "Articulos de Oficina");
            Product p5 = new Product(5, "Portaminas", "21809120", 6, "Artesco", "Articulos de Oficina");
            
            Client c1 = new Client("90909090", "Christian", "Dongo", new DateTime(1993,4,10), DateTime.Now, 999999999, "dongo@muere.net", 1, "3123123", "Preferencial");
            Client c2 = new Client("77777777", "Andrea", "Montoya", new DateTime(1993, 5, 29), DateTime.Now, 930285302, "gg@gg.net", 2, "4636346", "Normal");

            Salesclerk sc1 = new Salesclerk("4214214", "Gerardo", "Davila", new DateTime(1993, 6, 6), DateTime.Now, 91242141, "bbpig@pucp.pe", 1, "AGGGG");
            Salesclerk sc2 = new Salesclerk("6666666", "Gianina", "Ronceros", new DateTime(1993, 5, 30), DateTime.Now, 91242141, "grgr@pucp.pe", 2, "huheuhue");

            CashRegister cr1 = new CashRegister(1,"Caja Rapida");*/

            /*SalesManager.addProduct(p1);
            SalesManager.addProduct(p2);
            SalesManager.addProduct(p3);
            SalesManager.addProduct(p4);
            SalesManager.addProduct(p5);*/

            //SalesManager.PersistProductsDB();
            SalesManager.ReloadProductsDB();


            //SalesManager.addClient(c1);
            //SalesManager.addClient(c2);

            //SalesManager.PersistClientsDB();
            SalesManager.ReloadClientsDB();

            //SalesManager.addSalesclerk(sc1);
            //SalesManager.addSalesclerk(sc2);

            //SalesManager.PersistClerkDB();
            SalesManager.ReloadClerkDB();

            //SalesManager.addCr(cr1);

            //SalesManager.PersistCashRegisterDB();
            SalesManager.ReloadCashRegisterDB();
            SalesManager.ReloadSaleDB();
            SalesManager.ReloadCreditNoteDB();

           // Console.WriteLine(SalesManager.getProductbyId(2));
            
            //callMenu();
            login();            

            Console.ReadLine();

        }
    }
}
